package com.learning.thread.base.volatileexample;

/**
 * ClassName: VolatileUse
 * Description: VolatileUse 简单使用
 * Date: 2018/7/2 10:49 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class VolatileUse {

    private volatile boolean isExit;

    public void tryExit() {
        // 成立就退出
        if (isExit == !isExit) {
            System.exit(0);
        }
    }

    public void swapValue() {
        isExit = !isExit;
    }

    public static void main(String[] args) throws InterruptedException {
        final VolatileUse volatileUse = new VolatileUse();
        Thread mainThread = new Thread() {
            @Override
            public void run() {
                System.out.println("Main Thread start");
                while (true) {
                    // 不停的尝试时候可以退出
                    volatileUse.tryExit();
                }
            }
        };

        mainThread.setName("Main Thread");
        mainThread.start();

        Thread swapThread = new Thread() {
            @Override
            public void run() {
                System.out.println("Swap Thread start");
                while (true) {
                    // 不停的修改 isExit 的值
                    volatileUse.swapValue();
                }
            }
        };

        swapThread.setName("Swap Thread");
        swapThread.start();
        Thread.sleep(10000L);
    }
}
